package com.yq.ylmall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yq.ylmall.dto.product.BrandOperateDto;
import com.yq.ylmall.dto.product.RemoveDto;
import com.yq.ylmall.exception.ServiceException;
import com.yq.ylmall.model.product.Brand;
import com.yq.ylmall.product.mapper.BrandMapper;
import com.yq.ylmall.product.service.IBrandService;
import com.yq.ylmall.product.service.IFileService;
import com.yq.ylmall.result.ResultCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 分类品牌 服务实现类
 * </p>
 *
 * @author yzk789
 * @since 2024-05-31
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements IBrandService {

    private final IFileService fileService;

    @Override
    @Transactional
    public Boolean doUpdate(BrandOperateDto dto) {
        Brand brand = BeanUtil.copyProperties(dto, Brand.class);
        int row = baseMapper.updateById(brand);
        if (row == 0) return false;
        if (StrUtil.isNotBlank(dto.getOldImageUrl())) fileService.removeFile(dto.getOldImageUrl());
        return true;
    }

    @Override
    @Transactional
    public Boolean doRemoveById(RemoveDto dto) {
        int row = baseMapper.deleteById(dto.getId());
        if (row == 0) return false;
        if (StrUtil.isNotBlank(dto.getRemoveImg())) fileService.removeFile(dto.getRemoveImg());
        return true;
    }

    @Override
    @Transactional
    public Boolean doRemoveByIds(List<Long> ids) {
        int row = baseMapper.deleteBatchIds(ids);
        if (row == 0) {
            log.info("SQL执行异常：批量删除分类失败，ID：{}", ids.toString());
            return false;
        }
        List<Brand> brands = baseMapper.selectList(Wrappers.<Brand>lambdaQuery().select(Brand::getLogo).in(Brand::getId, ids));
        List<String> filenames = brands.stream().map(Brand::getLogo).collect(Collectors.toList());
        if (!filenames.isEmpty()) fileService.removeFile(filenames);
        return true;
    }

}
